package cc.linker.steplink.crm.merchanth5.controller.acs;

import cc.linker.steplink.crm.commons.Constants;
import cc.linker.steplink.crm.commons.domain.WxUser;
import cc.linker.steplink.crm.commons.utils.CalendarUtils;
import cc.linker.steplink.crm.merchanth5.commons.RequestFilter;
import cc.linker.steplink.crm.merchanth5.service.MaiBaoLaService;
import cc.linker.steplink.crm.merchanth5.service.MallService;
import cc.linker.steplink.crm.merchanth5.service.acs.MerchantWalletService;
import cc.linker.steplink.crm.merchanth5.service.common.SmsService;
import cc.linker.steplink.crm.response.GlobalException;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.mongodb.util.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * C端用户钱包
 */
@Slf4j
@RestController
@RequestMapping("/acs/merchantwallet")
public class MerchantWalletController {


    @Value("${wcpay.smsurl}")
    private String smsurl;

    @Autowired
    private MerchantWalletService merchantWalletService;
    @Autowired
    private MaiBaoLaService maiBaoLaService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private MallService mallService;
    @Autowired
    private RequestFilter requestFilter;

    /**
     * 钱包页面数据
     *
     * @param request
     * @return
     * @throws GlobalException
     */
    @GetMapping("/walletinfo")
    public Map<String, Object> walletInfo(HttpServletRequest request) throws GlobalException {
        WxUser wxUser =  requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        return merchantWalletService.walletInfo(customerId);
    }

    /**
     * 发送开通验证码
     */
    @PostMapping("/sendopencode")
    public Object sendOpenCode(@RequestBody Map<String, String> params, HttpServletRequest request) throws GlobalException {
        if (!params.containsKey("phone") || StringUtil.isEmpty(params.get("phone"))) {
            throw GlobalException.build("手机号未传");
        }
        WxUser wxUser =  requestFilter.getWxUser(request);
        String token = wxUser.getToken();
        if (merchantWalletService.mobileCount(params.get("phone"), wxUser.getCustomerId()) > 0) {
            throw GlobalException.build("该手机号已被绑定");
        }
        params.put("businessType", "1020");
//        params.put("smsurl", smsurl);
        params.put("token", token);
        return sendvercode(params);
    }

    private Object sendvercode(Map<String, String> params) throws GlobalException {
//        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
//        nvps.add(new BasicNameValuePair("businessType", params.get("businessType")));
//        nvps.add(new BasicNameValuePair("plantName", "STEPLINK"));
//        nvps.add(new BasicNameValuePair("mobilNumber", params.get("phone")));
//        nvps.add(new BasicNameValuePair("params", ""));
//        nvps.add(new BasicNameValuePair("token", ""));
//        String result = ParamSignUtils.callService(params.get("smsurl") + "/sms/sendVerificationCode", nvps, 0, 0);

        String token = params.get("token");
        String phone = params.get("phone");
        String result = smsService.sendVerification(token, phone);

        Object parse = JSON.parse(result);
        Map ret = (Map) parse;
        if ((Integer) ret.get("rt") != 1) {
            throw GlobalException.build("验证码发送失败");
        }
        return true;
    }


    /**
     * 通连模式H5端开通账户
     * @param params
     * @param request
     * @return
     * @throws Exception
     */
//    @PostMapping("/addtlaccount")
//    public Object addTlAccount(@RequestBody Map<String, Object> params, HttpServletRequest request) throws Exception {
//        WxUser wxUser =  requestFilter.getWxUser(request);
//        String customerId = wxUser.getCustomerId();
//        params.put("customerId",customerId);
//        params.put("accoutType","0");
//        params.put("clintType","yt");
//        params.put("customerType","11");
////        params.put("scale","8");
//        return merchantWalletService.capitalAccountApply(CommUtils.mapRemoveNull(params));
//    }


    /**
     * 申请提现账户
     */
    @PostMapping("/addaccount")
    public void addAccount(@RequestBody Map<String, String> params, HttpServletRequest request) throws Exception {
        WxUser wxUser =  requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        String orgId = wxUser.getOrgId();
        params.put("customerId", customerId);
        params.put("orgId", orgId);
        JSONObject object = merchantWalletService.addAccount(params);

        if (!object.containsKey("code")) {
            throw GlobalException.build("请求失败，请稍后重试");
        }
        if (!"200".equals(object.get("code").toString())) {
            throw GlobalException.build("开户失败，请稍后重试");
        }
    }

    /**
     * 实名认证接口 返回签名协议地址
     */
    @PostMapping("/setrealname")
    public Map<String, Object> setRealName(@RequestBody Map<String, String> params, HttpServletRequest request) {
        WxUser wxUser =  requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        String orgId = wxUser.getOrgId();
//        params.remove("jumpUrl");
        params.put("customerId", customerId);
        params.put("orgId", orgId);
        return merchantWalletService.setRealName(params);
    }

    /**
     * 提现界面
     *
     * @param request
     * @return
     * @throws GlobalException
     */
    @GetMapping("/getwithdraw")
    public Map<String, Object> getWithDraw(HttpServletRequest request) throws Exception {
        WxUser wxUser =  requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        return merchantWalletService.getWithDraw(customerId);
    }


    /**
     * 申请绑定银行卡
     */
    @PostMapping("/addbank")
    public void addBank(@RequestBody Map<String, String> params, HttpServletRequest request) throws Exception {
        WxUser wxUser =  requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        String orgId = wxUser.getOrgId();
        params.put("customerId", customerId);
        params.put("orgId", orgId);
        JSONObject object = merchantWalletService.addBank(params);
        if (object == null) {
            throw GlobalException.build("请求失败，请稍后重试!");
        }
        if (!object.containsKey("code")) {
            throw GlobalException.build("请求失败，请稍后重试");
        }
        if (!"200".equals(object.get("code").toString())) {
            throw GlobalException.build(object.get("msg").toString());
        }
    }


    /**
     * 激活绑定的银行卡
     */
    @PostMapping("/activebank")
    public void activeBank(@RequestBody Map<String, String> params, HttpServletRequest request) throws Exception {
        WxUser wxUser =  requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        String orgId = wxUser.getOrgId();
        params.put("customerId", customerId);
        params.put("orgId", orgId);
        JSONObject object = merchantWalletService.activeBank(params);
        if (!object.containsKey("code")) {
            throw GlobalException.build("请求失败，请稍后重试");
        }
        if (!"200".equals(object.get("code").toString())) {
            throw GlobalException.build(object.get("msg").toString());
        }
    }

    /**
     * 获取金币
     *
     * @return
     */
    @GetMapping("/getgoldcoin")
    public Map<String, Object> getGoldCoin(HttpServletRequest request) throws Exception {
        WxUser wxUser =  requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        return merchantWalletService.getGoldCoin(customerId);
    }

    /**
     * 发起提现
     *
     * @return
     */
    @PostMapping("/addwithdraw")
    public Map<String, String> addWithDraw(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        if (!params.containsKey("amount")) {
            throw GlobalException.build("请填写提现金额");
        }
        if (Float.valueOf(params.get("amount").toString()) == 0) {
            throw GlobalException.build("提现金额必须大于0元");
        }
        WxUser wxUser = requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        String orgId = wxUser.getOrgId();
        params.put("customerId", customerId);
        params.put("orgId", orgId);
        return merchantWalletService.addWithDraw(params);
    }

    /**
     * 获取提现详情
     *
     * @param request
     * @return
     * @throws GlobalException
     */
    @GetMapping("/getwithdrawdetail")
    public Map<String, Object> getWithDrawDetail(@RequestParam String withDrawId, HttpServletRequest request) throws Exception {
        Map<String, Object> params = new HashMap<>();
        WxUser wxUser =  requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        params.put("customerId", customerId);
        params.put("withDrawId", withDrawId);
        return merchantWalletService.getWithDrawDetail(params);
    }

    /**
     * 获取钱包明细
     *
     * @param pageSize
     * @param pageIndex
     * @param request
     * @return
     */
    @GetMapping("/detaillist")
    public PageInfo<Map<String, Object>> detailList(
            @RequestParam(defaultValue = "20") Integer pageSize,
            @RequestParam(defaultValue = "1") Integer pageIndex,
            HttpServletRequest request) {
        WxUser wxUser =  requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(merchantWalletService.detailList(customerId));
    }

    /**
     * 获取退款详情
     *
     * @return
     */
    @GetMapping("/getrefunddetail")
    public Map<String, Object> getRefundDetail(
            @RequestParam String protectCode,
            HttpServletRequest request) {
        Map<String, Object> params = new HashMap<>();
        WxUser wxUser =  requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        params.put("customerId", customerId);
        params.put("protectCode", protectCode);
        return merchantWalletService.getRefundDetail(params);
    }

    /**
     * 金币使用明细
     *
     * @param pageSize
     * @param pageIndex
     * @param request
     * @return
     */
    @GetMapping("/coinlist")
    public PageInfo<Map<String, Object>> coinList(
            @RequestParam(defaultValue = "20") Integer pageSize,
            @RequestParam(defaultValue = "1") Integer pageIndex,
            HttpServletRequest request) {
        WxUser wxUser =  requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(merchantWalletService.coinList(customerId));
    }

    /**
     * h5端发送手机验证码
     *
     * @param param
     * @param request
     * @return
     * @throws IOException
     * @throws URISyntaxException
     */
    @PostMapping("/sendverificationcode")
    public Boolean sendVerificationCode(@RequestBody Map<String, String> param, HttpServletRequest request) throws IOException, URISyntaxException {
        WxUser wxUser =  requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        String orgId = wxUser.getOrgId();
        if (StringUtils.isEmpty(customerId) || StringUtils.isEmpty(param.get("phone"))) {
            throw GlobalException.build("参数错误");
        }
        Integer payMode = mallService.getPayModeByOrgId(orgId);
        String alias = "";
        if(payMode == 3){
            alias = maiBaoLaService.getAliasByLinker();
        }
        if(payMode == 2){
            alias = maiBaoLaService.getAlias(orgId);
        }
        param.put("clintType", alias);
        param.put("customerId", customerId);
        return merchantWalletService.sendVerificationCode(param);
    }

    /**
     * 验证手机号
     *
     * @param param
     * @param request
     * @return
     * @throws IOException
     * @throws URISyntaxException
     */
    @PostMapping("/tosigncontract")
    public Map toSignContract(@RequestBody Map<String, String> param, HttpServletRequest request) throws IOException, URISyntaxException {
        WxUser wxUser =  requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        String orgId = wxUser.getOrgId();
        if (StringUtils.isEmpty(customerId) || StringUtils.isEmpty(param.get("jumpUrl")) || StringUtils.isEmpty(param.get("phone")) || StringUtils.isEmpty(param.get("verificationCode"))) {
            throw GlobalException.build("参数错误");
        }
        Integer payMode = mallService.getPayModeByOrgId(orgId);
        String alias = "";
        if(payMode == 3){
            alias = maiBaoLaService.getAliasByLinker();
        }
        if(payMode == 2){
            alias = maiBaoLaService.getAlias(orgId);
        }
        param.put("clintType", alias);
        param.put("jumpUrl", URLEncoder.encode(param.get("jumpUrl"), "utf-8"));
        param.put("customerId", customerId);
        return merchantWalletService.tosigncontract(param);
    }

    /**
     * 更换手机号
     *
     * @param param
     * @param request
     * @return
     * @throws IOException
     * @throws URISyntaxException
     */
    @PostMapping("/changephone")
    public Map changePhone(@RequestBody Map<String, String> param, HttpServletRequest request) throws IOException, URISyntaxException {
        WxUser wxUser =  requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        String orgId = wxUser.getOrgId();
        if (StringUtils.isEmpty(customerId) || StringUtils.isEmpty(param.get("jumpUrl")) || StringUtils.isEmpty(param.get("phone")) || StringUtils.isEmpty(param.get("verificationCode"))) {
            throw GlobalException.build("参数错误");
        }
        Integer payMode = mallService.getPayModeByOrgId(orgId);
        String alias = "";
        if(payMode == 3){
            alias = maiBaoLaService.getAliasByLinker();
        }
        if(payMode == 2){
            alias = maiBaoLaService.getAlias(orgId);
        }
        param.put("clintType", alias);
        param.put("jumpUrl", URLEncoder.encode(param.get("jumpUrl"), "utf-8"));
        param.put("customerId", customerId);
        return merchantWalletService.changePhone(param);
    }

    /**
     * 用户开户状态
     */
    @GetMapping("/accountStatus")
    public Map<String, Object> accountStatus(String jumpUrl, HttpServletRequest request) {
        WxUser wxUser =  requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        String orgId = wxUser.getOrgId();
        Map<String, Object> map = new HashMap<>();
        map.put("customerId", customerId);
        map.put("jumpUrl", jumpUrl);
        map.put("orgId", orgId);
        // 是否需要手机号
        map.put("flag", false);//2020-03-11修改为true
        return merchantWalletService.accountStatus(map);
    }


    /**
     * H5结算明细
     *
     * @param pageSize
     * @param pageIndex
     * @param request
     * @return
     */
    @GetMapping("/getsettlementdetail")
    public PageInfo<Map<String, Object>> getSettlementDetail(@RequestParam(defaultValue = "20") Integer pageSize,
                                                             @RequestParam(defaultValue = "1") Integer pageIndex,
                                                             HttpServletRequest request) {
        WxUser wxUser =  requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(merchantWalletService.getSettlementDetail(customerId));
    }

    /**
     * H5金币结算明细
     *
     * @param pageSize
     * @param pageIndex
     * @param request
     * @return
     */
    @GetMapping("/getscoresettlementdetail")
    public PageInfo<Map<String, Object>> getScoreSettlementDetail(@RequestParam(defaultValue = "20") Integer pageSize,
                                                                  @RequestParam(defaultValue = "1") Integer pageIndex,
                                                                  HttpServletRequest request) {
        WxUser wxUser =  requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(merchantWalletService.getScoreSettlementDetail(customerId));
    }
}
